<?php

// @formatter:off
/**
 * @file password.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: password.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/users/password.php $
 */
// @formatter:on

require_once __DIR__."/tools.php";

class WCServiceUsersPassword extends WCService {
	//
	// Class methods.
	public function __construct() {
		parent::__construct();

		$this->_readOnlyConflict = true;

		$this->_requiredParams["params"][] = "user";
		$this->_requiredParams["params"][] = "password";
		$this->_requiredParams["params"][] = "newpassword";
		$this->_requiredParams["params"][] = "hash";

		$this->_requiredPermissions["any"][] = WC_PERM_USER_EDIT;
		$this->_requiredPermissions["any"][] = WC_PERM_USER_SELF_EDIT;
		$this->_requiredPermissions["any"][] = WC_PERM_USER_RESET;
	}
	//
	// Protected methods.
	protected function load() {
		$out = false;

		if(parent::load()) {
			$this->hash = isset($this->hash) ? trim($this->hash) : false;
			$this->password = isset($this->password) ? trim($this->password) : false;
			$this->newpassword = isset($this->newpassword) ? trim($this->newpassword) : false;

			$out = true;
		}

		return $out;
	}
	protected function runPOST() {
		if(($wcUser && ($this->user == $wcUser->id() || $wcProfile->allowedTo(WC_PERM_USER_EDIT))) || ($this->hash && $wcProfile->allowedTo(WC_PERM_USER_RESET))) {
			global $wcUsersHolder;

			$user = $wcUsersHolder->item($this->user);
			if($user && $user->ok()) {
				if(($this->hash && $user->hash_reset == $this->hash) || $user->checkPassword(WCUser::EncryptPasswordString($this->password))) {
					if(!$user->setPassword($this->newpassword)) {
						$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "Unable to change password");
					} else {
						$this->_count++;
					}
				} elseif($user->hash_reset != $this->hash) {
					$this->setError(WC_HTTPERROR_BAD_REQUEST, "Current hash doesn't match");
				} else {
					$this->setError(WC_HTTPERROR_BAD_REQUEST, "Current password doesn't match");
				}
			} else {
				$this->setError(WC_HTTPERROR_BAD_REQUEST, "Not valid user");
			}
		} else {
			$this->setError(WC_HTTPERROR_UNAUTHORIZED, "You are not allowed to edit other users information");
		}
	}
}
